﻿//License:  New BSD License (BSD)
//Copyright (c) 2010, Jesper Lund Stocholm
//All rights reserved.

//Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

//* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

//* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

//* Neither the name of Jesper Lund Stocholm nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Web.Caching;
using System.Xml;
using System.Xml.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Xml.Schema;
using IS29500Validator.Models;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using IS29500Validator;
using IS29500Validator.Controllers;
//using Moq;

namespace IS29500Validator.Tests.Controllers
{
    [TestClass]
    public class HomeControllerTest
    {
        [TestMethod]
        public void Index()
        {
            // Arrange
            HomeController controller = new HomeController();

            // Act
            ViewResult result = controller.Index() as ViewResult;

            // Assert
            ViewDataDictionary viewData = result.ViewData;
            Assert.AreEqual("Welcome to the ISO/IEC 29500 Validator service", viewData["Message"]);
        }

        [TestMethod]
        public void About()
        {
            // Arrange
            HomeController controller = new HomeController();

            // Act
            ViewResult result = controller.About() as ViewResult;

            // Assert
            Assert.IsNotNull(result);
        }

        //[TestMethod]
        //public void FakeUploadFiles()
        //{
        //    //We'll need mocks (fake) of Context, Request and a fake PostedFile
        //    var request = new Mock<HttpRequestBase>();
        //    var context = new Mock<HttpContextBase>();
        //    var postedfile = new Mock<HttpPostedFileBase>();

        //    //Someone is going to ask for Request.File and we'll need a mock (fake) of that.
        //    var postedfilesKeyCollection = new Mock<HttpFileCollectionBase>();
        //    var fakeFileKeys = new List<string>() { "file" };

        //    //OK, Mock Framework! Expect if someone asks for .Request, you should return the Mock!
        //    context.Expect(ctx => ctx.Request).Returns(request.Object);
        //    //OK, Mock Framework! Expect if someone asks for .Files, you should return the Mock with fake keys!
        //    request.Expect(req => req.Files).Returns(postedfilesKeyCollection.Object);

        //    //OK, Mock Framework! Expect if someone starts foreach'ing their way over .Files, give them the fake strings instead!
        //    postedfilesKeyCollection.Expect(keys => keys.GetEnumerator()).Returns(fakeFileKeys.GetEnumerator());

        //    //OK, Mock Framework! Expect if someone asks for file you give them the fake!
        //    postedfilesKeyCollection.Expect(keys => keys["file"]).Returns(postedfile.Object);

        //    //OK, Mock Framework! Give back these values when asked, and I will want to Verify that these things happened
        //    postedfile.Expect(f => f.ContentLength).Returns(8192).Verifiable();
        //    postedfile.Expect(f => f.FileName).Returns("foo.doc").Verifiable();

        //    //OK, Mock Framework! Someone is going to call SaveAs, but only once!
        //    postedfile.Expect(f => f.SaveAs(It.IsAny<string>())).AtMostOnce().Verifiable();

        //    HomeController controller = new HomeController();
        //    //Set the controller's context to the mock! (fake)
        //    controller.ControllerContext = new ControllerContext(context.Object, new RouteData(), controller);

        //    //DO IT!
        //    ViewResult result = controller.UploadDocument() as ViewResult;

        //    //Now, go make sure that the Controller did its job
        //    var uploadedResult = result.ViewData.Model as List<ViewDataUploadFilesResult>;
        //    Assert.AreEqual(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "foo.doc"), uploadedResult[0].Name);
        //    Assert.AreEqual(8192, uploadedResult[0].Length);

        //    postedfile.Verify();
        //}

        [TestMethod]
        public void CanValidateValidTransitionalTextDocument()
        {
            string path = @"C:\Users\jst.DENMARK\projects\IS29500Validator\IS29500Validator.Tests\Files\Op og ned på OOXML.docx";

            FileStream fs = File.OpenRead(path);

            OOXMLDocument ooxmlDocument = new OOXMLDocument(fs, new FileInfo(path),  LoadXMLMapping(), LoadSchemaSet());

            ooxmlDocument.Validate();
        }

        [TestMethod]
        public void CanValidatesValidTransitionalTextDocument()
        {
            string path = System.Configuration.ConfigurationManager.AppSettings["TestFileLocation"] + "Projektforløb EL-Selvbetjening.docx";

            FileStream fs = File.OpenRead(path);

            OOXMLDocument ooxmlDocument = new OOXMLDocument(fs, new FileInfo(path), LoadXMLMapping(), LoadSchemaSet());

            ooxmlDocument.Validate();

            foreach (var line in ooxmlDocument.StatusLines)
                if (line.IsError)
                    Debug.WriteLine(line.Message);

            Assert.AreEqual(0, ooxmlDocument.StatusLines.Count);
        }

        XmlSchemaSet LoadSchemaSet()
        {
            var xmlSchemaSet = new XmlSchemaSet();


            string folderPath = System.Configuration.ConfigurationManager.AppSettings["SchemaLocationTransitional"]; //@"C:\Users\jst.DENMARK\projects\OOXMLValidator\OOXMLValidator\Schemas\Transitional";


            var directoryData = new DirectoryInfo(folderPath);
            var file = directoryData.GetFiles("*.xsd");
            foreach (var fileInfo in file)
            {
                xmlSchemaSet.Add(null, XmlReader.Create(System.IO.File.OpenRead(fileInfo.FullName)));
            }

            folderPath = System.Configuration.ConfigurationManager.AppSettings["SchemaLocationOPC"];

            directoryData = new DirectoryInfo(folderPath);
            file = directoryData.GetFiles("*.xsd");
            foreach (var fileInfo in file)
            {
                xmlSchemaSet.Add(null, XmlReader.Create(System.IO.File.OpenRead(fileInfo.FullName)));
            }

            return xmlSchemaSet;
        }

        [TestMethod]
        public void ParseFile()
        {
            string path = @"C:\Users\jst.DENMARK\projects\IS29500Validator\IS29500Validator\App_Data\Mapping.txt";

            FileStream fs = File.OpenRead(path);

            StreamReader reader = new StreamReader(fs);

            var dict = new Dictionary<string, ContentTypeRelationshipMap>();

            var conrel = new ContentTypeRelationshipMap();

            int i = 1;


            string line;

            while (reader.Peek() > 0)
            {
                Debug.WriteLine(i);
                line = reader.ReadLine().Trim();


                if (line == string.Empty)
                {
                    i = 0;
                    dict.Add(conrel.ContentType, conrel);
                    conrel = new ContentTypeRelationshipMap();
                }
                else
                {
                    if (i == 1)
                        conrel.Clause = line;

                    if (i == 2)
                        conrel.ContentType = line;

                    if (i == 3)
                        conrel.NamespaceName = line;

                    if (i == 4)
                        conrel.RelationshipType = line;

                    if (i == 5)
                        conrel.SchemaName = line;
                }

                i = i + 1;
            }

            DumpToXML(dict);
        }

        public void DumpToXML(Dictionary<string, ContentTypeRelationshipMap> dictionary_)
        {
            XDocument rootDoc = new XDocument();

            XElement xml = new XElement("OOXMLContentTypeRelationshipTypeMap",
                    from c in dictionary_.Keys
                    //orderby c.ContactId
                    select new XElement("MapData",
                              new XElement("Clause", dictionary_[c].Clause),
                              new XElement("ContentType", dictionary_[c].ContentType),
                              new XElement("NamespaceName", dictionary_[c].NamespaceName),
                              new XElement("RelationshipType", dictionary_[c].RelationshipType),
                              new XElement("SchemaName", dictionary_[c].SchemaName)
                    ));

            string s = xml.ToString();

            StreamWriter writer = File.CreateText("test.xml");

            writer.Write(s);

            writer.Flush();
            writer.Close();


        }

        [TestMethod]
        public void CanValidateValidTransitionalSpreadsheet()
        {
            Assert.IsNotNull(null);
        }

        [TestMethod]
        public void CanValidateValidTransitionalPresentation()
        {
            Assert.IsNotNull(null);
        }

        [TestMethod]
        public void CanDetectInvalidRelationshipType()
        {
            Assert.IsNotNull(null);
        }

        [TestMethod]
        public void CanDetectMissingPart()
        {
            Assert.IsNotNull(null);
        }

        [TestMethod]
        public void CanDetectInValidTransitionalTextDocument()
        {
            Assert.IsNotNull(null);
        }

        [TestMethod]
        public void CanDetectInValidTransitionalSpreadsheet()
        {
            Assert.IsNotNull(null);
        }

        [TestMethod]
        public void CanDetectInValidTransitionalPresentation()
        {
            string path = System.Configuration.ConfigurationManager.AppSettings["TestFileLocation"] + "nok er nok.pptx";

            FileStream fs = File.OpenRead(path);

            OOXMLDocument ooxmlDocument = new OOXMLDocument(fs, new FileInfo(path), LoadXMLMapping(), LoadSchemaSet());

            ooxmlDocument.Validate();
        }

        [TestMethod]
        public void CanValidateValidStrictTextDocument()
        {
            Assert.IsNotNull(null);
        }

        [TestMethod]
        public void CanValidateValidStrictSpreadsheet()
        {
            Assert.IsNotNull(null);
        }

        [TestMethod]
        public void CanValidateValidStrictPresentation()
        {
            Assert.IsNotNull(null);
        }

        [TestMethod]
        public void CanDetectInValidStrictTextDocument()
        {
            Assert.IsNotNull(null);
        }

        [TestMethod]
        public void CanDetectInValidStrictSpreadsheet()
        {
            Assert.IsNotNull(null);
        }

        [TestMethod]
        public void CanDetectInValidStrictPresentation()
        {
            Assert.IsNotNull(null);
        }

        private Dictionary<string, ContentTypeRelationshipMap> LoadXMLMapping()
        {
            XDocument xDocument = XDocument.Load(@"C:\Users\jst.DENMARK\projects\IS29500Validator\IS29500Validator\App_Data\mapping.xml");
            //XDocument xDocument = XDocument.Load("~/App_Data/mapping.xml");

            Dictionary<string, ContentTypeRelationshipMap> dict = new Dictionary<string, ContentTypeRelationshipMap>();

            var query = from d in xDocument.Descendants("MapData")
                        select new ContentTypeRelationshipMap()
                        {
                            Clause = d.Element("Clause").Value,
                            ContentType = d.Element("ContentType").Value,
                            NamespaceName = d.Element("NamespaceName").Value,
                            RelationshipType = d.Element("RelationshipType").Value,
                            SchemaName = d.Element("SchemaName").Value,
                        };

            foreach (var item in query)
            {
                //string s = item.ToString();
                dict.Add(item.ContentType, item);
            }


            return dict;

        }

    }


}
